<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.goods_delete"
                   @click="handleDelete">删 除
        </el-button>
      </template>
      <template slot-scope="{row}"
                slot="price">
        <el-tag v-if="!row.price || row.price === -1">无</el-tag>
        <el-tag v-else>{{row.price}} 元</el-tag>
      </template>
      <template slot-scope="{row}"
                slot="vipPrice">
        <el-tag v-if="!row.vipPrice || row.vipPrice === -1">无</el-tag>
        <el-tag v-else>{{row.vipPrice}} 元</el-tag>
      </template>
      <template slot-scope="{row}"
                slot="categoryId">
        <span
          v-if="row.categoryName.split(',').length > 0 && row.categoryName !== ''"
          :key="key" v-for="(name, key) in row.categoryName.split(',')"
        >
          <el-tag
            size="small"
            type="success"
          >{{name}}</el-tag>&nbsp;
        </span>
      </template>
      <template slot-scope="{row}"
                slot="labelId">
        <span
          v-if="row.labelName.split(',').length > 0 && row.labelName !== ''"
          :key="key" v-for="(name, key) in row.labelName.split(',')"
        >
          <el-tag
            size="small"
            type="success"
          >{{name}}</el-tag>&nbsp;
        </span>
      </template>
      <template slot-scope="{row}"
                slot="specificationId">
        <span v-if="row.specificationName.split(',').length > 0 && row.specificationName !== ''"
              :key="key" v-for="(name, key) in row.specificationName.split(',')">
          <el-tag
            size="small"
            type="success"
          >{{name}}</el-tag>&nbsp;
        </span>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove} from "@/api/goods/goods";
  import {getSelect as getCategoryList} from "@/api/goods/goods_category";
  import {getSelect as getLabelList} from "@/api/goods/goods_label";
  import {getSelect as getSpecificationList} from "@/api/goods/goods_specification";
  import {mapGetters} from "vuex";

  export default {
    data() {
      return {
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 100,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height: 'auto',
          calcHeight: 210,
          searchShow: true,
          searchMenuSpan: 6,
          tip: false,
          border: true,
          index: true,
          viewBtn: false,
          menuWidth: '300',
          menuType: 'button',
          selection: true,
          column: [
            {
              label: "商品名称",
              prop: "name",
              rules: [{
                required: true,
                message: "请输入商品名称",
                trigger: "blur"
              }]
            },
            {
              label: "类型",
              prop: "categoryId",
              multiple: true,
              type: "select",
              dicData: [],
              props: {
                label: "name",
                value: "id"
              },
              slot: true,
              rules: [{
                required: true,
                message: "请选择类型",
                trigger: "blur"
              }]
            },
            {
              label: "规格",
              prop: "specificationId",
              multiple: true,
              type: "select",
              dicData: [],
              props: {
                label: "name",
                value: "id"
              },
              slot: true
            },
            {
              label: "排序",
              prop: "sort",
              value: 99,
              type: "number"
            },
            {
              label: "标签",
              prop: "labelId",
              multiple: true,
              type: "select",
              dicData: [],
              props: {
                label: "name",
                value: "id"
              },
              slot: true
            },
            {
              label: "价格",
              prop: "price",
              type: "number",
              slot: true,
              rules: [{
                required: true,
                message: "请输入价格",
                trigger: "blur"
              }]
            },
            {
              label: "会员价",
              prop: "vipPrice",
              type: "number",
              slot: true,
            },
            {
              label: "封面图片",
              prop: "pictureUrl",
              dataType: 'string',
              type: 'upload',
              span: 24,
              listType: 'picture-card',
              propsHttp: {
                res: 'data',
                url: 'link',
                name: 'originalName'
              },
              limit: 9,
              tip: '只能上传jpg/png文件，且不超过500kb, 限制9张图片',
              action: '/api/blade-resource/oss/endpoint/put-file',
              hide: true
            },
            {
              label: "描述",
              prop: "description",
              type: "ueditor",
              component: 'avue-ueditor',
              action: "/api/blade-resource/oss/endpoint/put-file",
              propsHttp: {
                res: "data",
                url: "link"
              },
              options: {
                customConfig: {
                  uploadImgMaxSize: 30 * 1024 *1024
                },
              },
              span: 24,
              hide: true
            }
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.goods_add, false),
          viewBtn: this.vaildData(this.permission.goods_view, false),
          delBtn: this.vaildData(this.permission.goods_delete, false),
          editBtn: this.vaildData(this.permission.goods_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      rowSave(row, done, loading) {
        row.categoryId = row.categoryId.join(",");
        row.labelId = row.labelId.join(",");
        row.specificationId = row.specificationId.join(",");
        add(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowUpdate(row, index, done, loading) {
        row.categoryId = row.categoryId.join(",");
        row.labelId = row.labelId.join(",");
        row.specificationId = row.specificationId.join(",");
        update(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;

            if (this.form.price === -1) {
              this.form.price = 0
            }
            if (this.form.vipPrice === -1) {
              this.form.vipPrice = 0
            }

            if(this.form.hasOwnProperty("categoryId")){
              this.form.categoryId = (this.form.categoryId === undefined || this.form.categoryId === '')
              ? [] : this.form.categoryId.split(",");
            }
            if(this.form.hasOwnProperty("labelId")){
              this.form.labelId = (this.form.labelId === undefined || this.form.labelId === '')
              ? [] : this.form.labelId.split(",");
            }
            if(this.form.hasOwnProperty("specificationId")){
              this.form.specificationId = (this.form.specificationId === undefined || this.form.specificationId === '')
                ? [] : this.form.specificationId.split(",");
            }
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
        getCategoryList().then(res => {
          const column = this.findObject(this.option.column, "categoryId");
          column.dicData = res.data.data;
        });
        getLabelList().then(res => {
          const column = this.findObject(this.option.column, "labelId");
          column.dicData = res.data.data;
        });
        getSpecificationList().then(res => {
          const column = this.findObject(this.option.column, "specificationId");
          column.dicData = res.data.data;
        });
      }
    }
  };
</script>

<style>
</style>
